package com.myjob.serviceImpl;

import cn.hutool.Hutool;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.myjob.common.DubboConfig;
import com.myjob.config.MjServiceName;
import com.myjob.config.PrivateKeyProperties;
import com.myjob.dto.KeyPairDto;
import com.myjob.entity.*;
import com.myjob.enums.RedisEnums;
import com.myjob.enums.UserEnums;
import com.myjob.exception.DBOptionException;
import com.myjob.exception.OptionException;
import com.myjob.handler.CompanyHandler;
import com.myjob.response.Result;
import com.myjob.service.*;
import com.myjob.utils.*;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.KeyPair;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author chenyuan
 * @date 2021/1/17 11:57
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private BaseInfoService baseInfoService;
    @Reference(group = MjServiceName.COMPANY, version = DubboConfig.VERSION)
    private CompanyHandler companyHandler;

    @Override
    public Integer loginWithPassword(String username, String password) {
        User user = userService.selectByPhoneOrEmil(username);
        if (UtilValidate.isEmpty(user)) {
            // -1 表示用户名错误
            return -1;
        }

        boolean matches = BPwdEncoderUtil.matches(password, user.getPassword());

        // 1 表示用户名密码正确  ; -2 表示密码错误
        return matches ? 1 : -2;
    }

    @Override
    public Integer loginWithCode(String username, String code, Map<String, String> resultMap) {
        User user = userService.selectByPhoneOrEmil(username);
        if (UtilValidate.isEmpty(user)) {
            // -1 表示用户名错误
            return -1;
        }

        String codeCache = String.valueOf(redisUtil.get(RedisEnums.KEY_IN_REDIS.EMAIL_CODE.getValue() + username));
        if (UtilValidate.isEmpty(codeCache)) {
            // -2 表示验证码过期
            return -2;
        }
        // 1 表示信息正确 ; -3 表示验证码错误
        resultMap.put("password",user.getPassword());
        return code.equals(codeCache) ? 1 : -3;
    }

    @Override
    public Boolean phoneIsExist(String phone) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        List<User> list = userService.list(wrapper);
        return UtilValidate.isNotEmpty(list);
    }

    @Override
    public Boolean emailIsExist(String email) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email", email);
        List<User> list = userService.list(wrapper);
        return UtilValidate.isNotEmpty(list);
    }

    @Override
    public String sendCode(String email) {
        String code = RandomUtil.randomString(6).toUpperCase();
        EmailUtil.send_email(email, code);
        redisUtil.set(RedisEnums.KEY_IN_REDIS.EMAIL_CODE.getValue()+email, code, 2, TimeUnit.MINUTES);
        log.info("成功发送邮件,验证码为："+code);
        return code;
    }

    @Override
    @GlobalTransactional(rollbackFor = {DBOptionException.class, RuntimeException.class, Exception.class})
    public Boolean registerAccount(User user) {
        String tempRole = user.getRole();
        String role = "";
        if (Objects.equals(tempRole, "company")) {
            role = UserEnums.ROLE.company.getValue();
        }else {
            role = UserEnums.ROLE.candidate.getValue();
        }

        String password = user.getPassword();
        password = BPwdEncoderUtil.BCryptPassword(password);

        user.setPassword(password);
        user.setRole(role);
        user.setAccountStatus(UserEnums.ACCOUNT_STATUS.normal.getValue());
        boolean save = userService.save(user);

        if (Objects.equals(tempRole, "company")) {
            log.info("[Dubbo] - 远程调用开始 -> "+MjServiceName.COMPANY+" -> companyHandler -> addCompany");
            Company company = new Company();
            company.setCompanyId(user.getUserId());
            companyHandler.addCompany(company);
            log.info("[Dubbo] - 远程调用结束 -> =======================================================");
        }else {
            BaseInfo baseInfo = new BaseInfo();
            baseInfo.setUserId(user.getUserId());
            baseInfo.setEmail(user.getEmail());
            baseInfo.setPhone(user.getPhone());
            baseInfo.setName(user.getUserName());
            baseInfoService.insertBaseInfo(baseInfo);
        }

        return save;
    }


}
